package com.dlc.felear.xiaoensale.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.dlc.felear.xiaoensale.R;
import com.dlc.felear.xiaoensale.adapter.FoodMaterial_1_Adapter;
import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.customView.ConfirmDialog;
import com.dlc.felear.xiaoensale.customView.ShowTispMsgDialog;
import com.dlc.felear.xiaoensale.dao.MenuFoodMaterialDao;
import com.dlc.felear.xiaoensale.deviceUtil.Serialhelper;
import com.dlc.felear.xiaoensale.deviceUtil.TopbarHelper;
import com.dlc.felear.xiaoensale.dlc_serial_port.DlcSerialPortClient;
import com.dlc.felear.xiaoensale.entity.MenuFoodMaterial;
import com.dlc.felear.xiaoensale.entity.Msg;
import com.dlc.felear.xiaoensale.entity.WeightInfo;
import com.dlc.felear.xiaoensale.factory.OrderFactory;
import com.dlc.felear.xiaoensale.helper.SendData;
import com.dlc.felear.xiaoensale.utils.InputMethodManagerUtil;
import com.dlc.felear.xiaoensale.utils.NumToStringUtil;
import com.itdlc.android.library.base.BaseActivity;
import com.itdlc.android.library.listener.TextWatcherAdapter;
import com.itdlc.android.library.utils.APPDidUtil;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 云端称——称毛重
 */

public class  RoughWeightActivity extends BaseActivity implements Handler.Callback,ConfirmDialog.ConfirmDialogCallback {
    private static final String TAG = "RoughWeightActivity";
    private TopbarHelper topbarHelper;
    private FoodMaterial_1_Adapter adapter;
    private MenuFoodMaterialDao foodMaterialDao;
    @BindView(R.id.s_gv)
    GridView gv;
    @BindView(R.id.s_tv_name)
    TextView tvName;
    @BindView(R.id.s_tv_weight)
    TextView tvWeight;
    @BindView(R.id.s_et_name)
    EditText etName;
    private long weight = 300;
    private int lastFoodId = -1;
    private long lastFoodWeight = 0;
    private MenuFoodMaterial foodMaterial;
    private long totalWeight=0;
    private boolean isHide=false;
    private ShowTispMsgDialog showTispMsgDialog;
    private Handler handler;
    private ConfirmDialog confirmDialog;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_rough_weight;
    }

    @Override
    protected void initialView() {
        EventBus.getDefault().register(this);
        foodMaterialDao = new MenuFoodMaterialDao(this);
        topbarHelper = new TopbarHelper(this);
        topbarHelper.setcon(R.drawable.small_clock_icon);
        topbarHelper.setNavActivity(FirstActivity.class);
        topbarHelper.setReturnEnable(true);
        adapter = new FoodMaterial_1_Adapter(this);
        gv.setAdapter(adapter);
        handler=new Handler(this);
        showTispMsgDialog=new ShowTispMsgDialog(this);
        EventBus.getDefault().post(1,Constant.POND_SIZE);
        confirmDialog=new ConfirmDialog(this,this);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                foodMaterial = adapter.getItem(position);
                tvName.setText(foodMaterial.getFoodName());
                InputMethodManagerUtil.inputMethodStatus(RoughWeightActivity.this,etName,false);
            }
        });
        etName.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                Log.e(TAG, "s=" + s.toString());
                adapter.setItems(foodMaterialDao.queryForAllByName(s.toString(),Constant.FOODS_TYPE_1));
            }
        });
    }


    @Override
    protected void initData() {
        String appId = APPDidUtil.getAppDid();
        int length = appId.length();
        topbarHelper.setTitle("食材入库_设备编号：" + appId.substring(length - 4, length));
    }
    @Override
    protected void onResume() {
        super.onResume();
        isHide=false;
        adapter.setItems(foodMaterialDao.queryForAll((Constant.FOODS_TYPE_1)));
    }

    @Override
    protected void onStop() {
        super.onStop();
        isHide=true;
    }

    @OnClick({R.id.s_btn_clear, R.id.s_btn_save, R.id.s_iv_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.s_btn_clear:
                reSetWeight();
                break;
            case R.id.s_btn_save:
                if(foodMaterial!=null){
                    confirmDialog.showDialog("确定上传:"+foodMaterial.getFoodName(),1);
                }else {
                    showShortToast("请先选择上传的食材");
                }
                break;
            case R.id.s_iv_search:
                adapter.setItems(foodMaterialDao.queryForAll((Constant.FOODS_TYPE_1)));
                break;
        }
    }

    private void reSetWeight(){
        byte[] data=OrderFactory.tieboshiResetZero(1,0);//置零
        DlcSerialPortClient.getInstance().send(Serialhelper.getInstance().getWeightSerialPort(1), data);
        tvWeight.setText(Integer.toString(0));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (requestCode == 1025) {
                String foodName = data.getExtras().getString(Constant.FOOD_NAME);
                int id = data.getExtras().getInt(Constant.FOOD_ID);
                tvName.setText(foodName);
                foodMaterial=new MenuFoodMaterial(foodName);
                foodMaterial.setFoodid(id);
            }
        } catch (Exception e) {
            showShortToast("数据异常");
        }
    }

    @Subscriber(tag = Constant.EVENTBUS_TAG_HTTP_RESULT)
    public void recieveHttpResult(Msg msg) {
        Log.e(TAG,msg.getMsg());
        if(!TextUtils.isEmpty(msg.getMsg())){
            showMsgForDialog(changeMsg(msg.getMsg()));
        }else if(!TextUtils.isEmpty(msg.getMessage())){
            showShortToast(msg.getMessage());
        }
    }

    private String changeMsg(String msg){
        if(msg.contains("操作成功")){
            return "入库完成";
        }
        return msg;
    }

    private void showMsgForDialog(String msg){
        if(showTispMsgDialog!=null){
            showTispMsgDialog.setMsg(msg);
            showTispMsgDialog.setDialog(msg);
            handler.sendEmptyMessageDelayed(1211,2000);
        }
    }
    private void closeDialog(){
        if(showTispMsgDialog!=null){
            showTispMsgDialog.closeDialog();
        }
    }

    @Subscriber(tag = Constant.EVENTBUS_TAG_ACTION_TAKE_PUT)
    public void recieve(WeightInfo weightInfo) {
        if(isHide){
            return;
        }
        Log.e(TAG, "weight=" + weightInfo.getWeight());
        if (Math.abs(this.weight - weightInfo.getWeight()) < 3) {
            return;
        }
        this.weight = weightInfo.getWeight();
        totalWeight=weightInfo.getWeight();
        double tetmm=(double)weight/1000;
        tvWeight.setText(NumToStringUtil.spitDouble(tetmm,3)+"斤");
    }

    private void save() {
        try {
            if (foodMaterial == null || TextUtils.isEmpty(foodMaterial.getFoodName())) {
                showShortToast("请选择食材");
                return;
            }
            if (Math.abs(lastFoodWeight - totalWeight) < 5 && foodMaterial.getFoodid()==lastFoodId) {
                showShortToast("请不要重复入库");
                return;
            }
            upLoadData(weight, foodMaterial.getFoodid());
        } catch (Exception e) {
            showShortToast("数据异常");
        }

    }



    private void upLoadData(long weight, int id) {
        if(weight<=50){
            showShortToast("重量数值太小");
          return;
        }
        foodMaterial.setWeight(weight);
        foodMaterial.setNumber(1);
        List<MenuFoodMaterial> list=new ArrayList<>();
        list.add(foodMaterial);
        SendData.uplaodFoodMaterial(list,1);
        lastFoodWeight = weight;
        lastFoodId = id;
    }

    @Override
    public boolean handleMessage(Message msg) {
        closeDialog();
        return false;
    }

    @Override
    public void selectResult(int value, int id) {
        if(value==1){
            save();
        }
    }
}
